<?php

Loader::using("ext::libs::inscripcionesGenericas::QuestionBasedUIControlFilter");
Loader::using("ext::libs::phpUI::DataSet");

class DataSourceDataSetUIControlFilter extends QuestionBasedUIControlFilter {

    public function &filterControl(UIControl &$newInstance) {
        if ($newInstance instanceof DataSet) {
            $params = $this->getDecodedParams();
            if (isset($params->dataset)) {
                $this->doFilter($newInstance, $params->dataset);
                
                if (isset($params->dataset->default)) {
                    $newInstance->setValue($params->dataset->default);
                }
            }
        }

        return $newInstance;
    }

    private function doFilter(DataSet &$control, $config) {
        $model = self::model()->load($config->Model);

        $reflectionClass = new ReflectionClass($model);
        /* @var $method ReflectionMethod */
        $method = $reflectionClass->getMethod($config->Method);
        $result = $method->invokeArgs($model, $config->Params);
        $options = $control->getOptions();

        foreach ($result as $object) {
            if (is_object($object)) {
                $key = $object->{"get" . $config->Value}();
                $value = $object->{"get" . $config->Text}();

                $options[$key] = $value;
            } else {
                $options[$object] = $object;
            }
        }

        $control->setOptions($options);
    }

    /**
     *
     * @var modelLoader
     */
    private static $modelInstance;

    /**
     *
     * @return modelLoader
     */
    protected static function model() {
        if (self::$modelInstance == null) {
            self::$modelInstance = new modelLoader();
            self::$modelInstance->setModuleName("InscripcionesGenericas");
        }

        return self::$modelInstance;
    }

}

?>